package longrise.phone.com.bjjt_henan.compensate;

import android.content.Context;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.LFView;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerCar;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.UiUtil;

import longrise.phone.com.bjjt_henan.Constant.URLConstant;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.Utils.DialogUtils;


/**
 * 事故类型状态选择界面
 */
public class NewSelectAccidentView extends LFView implements OnClickListener {

    private Context mContext = null;
    private View mView = null;
    private ListView mListView;
    private EditText infoEText;
    private Button mBtn;
    // 全局applicaton
    private BaseApplication mApplication;
    private String appCaseno;
    private EntityBean myDrivingLiscenceBean;

    public NewSelectAccidentView(Context c, String caseNo, EntityBean myDrivingLiscenceBean) {
        super(c);
        this.mContext = c;
        this.mApplication = (BaseApplication) c.getApplicationContext();
        this.appCaseno = caseNo;
        this.myDrivingLiscenceBean = myDrivingLiscenceBean;
    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter fp = new FormParameter();
        fp.setShowtitle(false);
        return fp;
    }

    @Override
    public View getView() {
        return mView;
    }

    @Override
    public void init() {
        LayoutInflater inflater = null;
        if (null != mContext) {
            inflater = LayoutInflater.from(mContext);
        }
        if (null != inflater) {
            mView = inflater.inflate(R.layout.view_accidentselect_new,
                    null);
        }
        if (null == mView) {
            return;
        }
        //标题栏
        TextView titleTV = (TextView) mView.findViewById(R.id.tv_title);
        titleTV.setText("选择事故形态");
        mView.findViewById(R.id.hn_btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeForm();
                OnDestroy();
            }
        });
        mListView = (ListView) mView.findViewById(R.id.accident_select_listview);
        infoEText = (EditText) mView.findViewById(R.id.accident_select_edittext);
        mBtn = (Button) mView.findViewById(R.id.accident_select_btn);
        regEvent(true);
        //列表设置为多选模式
        mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, R.layout.item_list_multiple_choice,
                R.id.checktv1, CommontUtils.getAccidentTypes());
        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int count = mListView.getCheckedItemCount();
                if (count > 3) {
                    UiUtil.showToast(mContext, "最多同时选择3种事故情形！");
                    //模拟点击反选取消选中
                    mListView.performItemClick(view, position, id);
                    return;
                }
                adapter.notifyDataSetChanged();
            }
        });

        infoEText.setFilters(new InputFilter[]{new MaxLengthFilter(80, mContext)});
    }

    //增加输入长度的限制提示
    public static class MaxLengthFilter implements InputFilter {
        private final int mMax;
        private Context context;

        public MaxLengthFilter(int max, Context context) {
            mMax = max;
            this.context = context;
        }

        public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                                   int dstart, int dend) {
            int keep = mMax - (dest.length() - (dend - dstart));
            if (keep < (end - start)) {
                UiUtil.showToast(context, "最多只能写80字！");
            }
            if (keep <= 0) {
                return "";
            } else if (keep >= end - start) {
                return null; // keep original
            } else {
                keep += start;
                if (Character.isHighSurrogate(source.charAt(keep - 1))) {
                    --keep;
                    if (keep == start) {
                        return "";
                    }
                }
                return source.subSequence(start, keep);
            }
        }

        /**
         * @return the maximum length enforced by this input filter
         */
        public int getMax() {
            return mMax;
        }
    }

    /**
     * 获取选中的类型字符串
     *
     * @return
     */
    private String getSelectType() {
        StringBuffer selectType = null;
        //获取选中项的位置
        SparseBooleanArray array = mListView.getCheckedItemPositions();
        int size = array.size();
        for (int i = 0; i < size; i++) {
            int index = array.keyAt(i);
            if (mListView.getCheckedItemPositions().get(index)) {//移除反选取消的
                if (TextUtils.isEmpty(selectType)) {
                    selectType = new StringBuffer();
                }
                selectType.append(index + 1).append(",");
            }
        }
        if (TextUtils.isEmpty(selectType)) {
            return null;
        } else {
            String select = selectType.toString();
            if (select.endsWith(",")) {
                select = select.substring(0, select.length() - 1);
            }
            return select;
        }
    }

    private void regEvent(boolean flag) {
        if (null != mBtn) {
            mBtn.setOnClickListener(flag ? this : null);
        }
    }

    @Override
    public void refresh() {

    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public void OnDestroy() {
        regEvent(false);
        mView = null;
        mListView = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.accident_select_btn:
                if (null == myDrivingLiscenceBean) {
                    checkDrivingLicence();
                } else {
                    accidentInfo();
                }
                break;
            default:
                break;
        }
    }

    private void accidentInfo() {
        String selectType = getSelectType();
        if (TextUtils.isEmpty(selectType)) {
            UiUtil.showToast(mContext, "请选择事故形态");
            return;
        }

        //补充说明
        String info = infoEText.getText().toString().trim();
        //进入事故填写界面
        AccidentLoadingView accidentloadingview = new AccidentLoadingView(mContext, appCaseno,
                myDrivingLiscenceBean, selectType, info);
        FrameworkManager.getInstance().showNewForm(mContext, accidentloadingview);
    }

    //根据车主姓名查询驾驶证信息
    private void checkDrivingLicence() {
        EntityBean bean = new EntityBean();
        EntityBean userInfo = mApplication.getLoginInfo().getBean("userinfo");
        bean.set("username", mApplication.getKckpName());
        bean.set("carownername", userInfo.get("name"));
        bean.set("token", mApplication.getToken());
        DialogUtils.showDialog(mContext);
        LoadDataManagerCar.getInstance(mContext).callService(null,
                mApplication.getServerUrl(), URLConstant.KCKPAPPGETCAROWNER, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        String redes = bean.getString("redes");
                        if ("1".equals(restate)) {
                            myDrivingLiscenceBean = bean.getBean("data");
                            accidentInfo();
                        } else {
                            UiUtil.showToast(mContext, redes);
                        }
                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        if (resultType == LoadDataManagerFather.ResultType.Failure) {
                            UiUtil.showToast(mContext, "连接超时，请检查网络后重试。");
                        } else if (resultType == LoadDataManagerFather.ResultType.NoNetWorks) {
                            UiUtil.showToast(mContext, "无网络连接，请检查您的网络");
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        DialogUtils.closeDialog();
                    }
                });
    }

}
